package com.ls.aicoderbackend.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.ls.aicoderbackend.ai.model.HtmlCodeResult;
import com.ls.aicoderbackend.ai.model.MultiFileCodeResult;
import com.ls.aicoderbackend.model.enums.CodeGenTypeEnum;

import java.io.File;
import java.nio.charset.StandardCharsets;
@Deprecated
public class CodeFileSaver {

    // 文件保存在根目录
    private static final String FILE_SAVE_ROOT_DIR = System.getProperty("user.dir") + "/tmp/code_output";


    // 保存HtmlCodeResult的内容
    public static File saveHtmlCodeResult(HtmlCodeResult htmlCodeResult) {
        String basicDirPath = buildUniqueDir(CodeGenTypeEnum.HTML.getValue());
        writeToFile(basicDirPath, "index.html", htmlCodeResult.getHtmlCode());
        return new File(basicDirPath);
    }

    // 保存MultiFileCodeResult的内容
    public static File saveMultiFileCodeResult(MultiFileCodeResult multiFileCodeResult) {
        String basicDirPath = buildUniqueDir(CodeGenTypeEnum.MULTI_FILE.getValue());
        writeToFile(basicDirPath, "index.html", multiFileCodeResult.getHtmlCode());
        writeToFile(basicDirPath, "style.css", multiFileCodeResult.getCssCode());
        writeToFile(basicDirPath, "script.js", multiFileCodeResult.getJsCode());
        return new File(basicDirPath);
    }

    // 构建唯一路径, 并创建目录
    private static String buildUniqueDir(String bizType) {
        String uniqueName = StrUtil.format("{}_{}", bizType, IdUtil.getSnowflakeNextIdStr());
        String dirPath = FILE_SAVE_ROOT_DIR + File.separator + uniqueName;
        // 创建目录
        FileUtil.mkdir(dirPath);
        return dirPath;
    }

    // 将文件写入到具体目录中
    private static void writeToFile(String dirPath, String fileName, String content) {
        String filePath = dirPath + File.separator + fileName;
        FileUtil.writeString(content, filePath, StandardCharsets.UTF_8);
    }
}
